<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author Cheng
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'firehazardprocess::edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="60%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm" />

    <div class="fireVeIm">
      <div class="fireImg">
        <span>
          异常图片:
        </span>
        <Image v-if="imageFire" :src="imageFire" width="100%" height="100%"></Image>
        <img v-else  src="/@/assets/images/noData.png" alt="">
      </div>
      <div class="fireImg">
        <span>
          处理结果图片:
        </span>
        <Image v-if="imageResult" :src="imageResult" width="100%" height="100%"></Image>
        <img v-else src="/@/assets/images/noData.png" alt="">
      </div>
    </div>

    <template #footer>
      <BpmButton
        v-model:bpmEntity="record"
        v-show="record.currentlyTimeout!=='是'"
        bpmEntityKey="id"
        formKey="Fire_Hazard_Process"
        completeText="提交"
        :completeModal="true"
        :loading="loadingRef"
        :auth="'firehazardprocess::edit'"
        @validate="handleValidate"
        @user-select="handleUserSelect"
        @complete="handleSubmit"
        @success="handleSuccess"
        @close="closeDrawer"
      />
    </template>
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsFirehazardprocessForm">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { FireHazardProcess, fireHazardProcessSave, fireHazardProcessForm } from '/@/api/firehazardprocess/fireHazardProcess';
  import { BpmButton } from '/@/components/Bpm';
  import { officeTreeData } from '/@/api/sys/office';
  import { unitBuildingListData } from '/@/api/unitmanage/unitBuilding';
  import { unitRegionListData } from '/@/api/unitmanage/unitRegion'; 
  import { bpmProcInsTrace } from '/@/api/bpm/runtimeDisplay';
  import {empUserListData} from '/@/api/sys/empUser';
  import { Image } from 'ant-design-vue'


  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('firehazardprocess.fireHazardProcess');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<FireHazardProcess>({ 
   currentlyTimeout: '否', 
    bpm: {}
   } as FireHazardProcess);
  const loadingRef = ref(false);
  
 const FormResult=ref<any>({})

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增消防隐患流程表') : t('编辑消防隐患流程表'),
  }));

  const imageFire = ref()
  const imageResult = ref()
  const userParams = ref<Recordable>({name:''})

  const inputFormSchemas: FormSchema[] = [

  {
      label: t('分配人姓名'),
      field: 'assignerId',
      fieldLabel:'assignerName',
      show:()=>{
       return record.value.bpm.activityId=='assign_personnel'
      },
      component: 'Select',
      componentProps: () => {
        return {
          api: empUserListData,
          params: userParams.value,
          fieldNames: { label: 'userName', value: 'userCode' },
          resultField: 'list',
          notFoundContent: '未查询到记录',
          filterTreeNode: false,
          allowClear: true,
          filterOption: false,
          immediate: true,
          onSearch: (value: string) => {
            userParams.value.userName = value;
            console.log(userParams.value);
          },
        };
      },
      required: true
    },
    {
      label: t('上报人'),
      field: 'reportPersonName',
      // fieldLabel:'enterpriseName',
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true
      },
    },
    {
      label: t('上报电话'),
      field: 'reportPersonPhone',
      // fieldLabel:'enterpriseName',
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true
      },
    },
    {
      label: t('上报人'),
      field: 'reportPerson',
      // fieldLabel:'enterpriseName',
      show: false,  
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true
      },
    },
    {
      label: t('隐患类型'),
      field: 'hazardType',
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true
      },
    },
    {
      label: t('企业名称'),
      field: 'enterpriseName',
      component: 'TreeSelect',
      componentProps: {
        maxlength: 255,
        api:officeTreeData,
        params:{},
        onChange:(name,id)=>{
          record.value.enterpriseName = name;
          record.value.enterpriseId = id;
        },
        disabled: true
      },
    },
    {
      label: t('建筑名称'),
      field: 'buildName',
      component: 'Select',
      componentProps: {
        maxlength: 255,
        api:unitBuildingListData,
        params:{},
        resultField:'list',
        onChange:(name,id)=>{
          record.value.buildName = name;
          record.value.buildId = id;
        },
        fieldNames:{
          label:'name',
          value:'id'
        },
        disabled: true
      },
    },
    {
      label: t('区域名称'),
      field: 'regionName',
      component: 'Select',
      componentProps: {
        maxlength: 255,
        api:unitRegionListData,
        params:{},
        resultField:'list',
        onChange:(name,code)=>{
          record.value.regionName = name;
          record.value.regionId = code;
        },
        fieldNames:{
          label:'name',
          value:'id'
        },
        disabled: true
      },
    },
    {
      label: t('隐患地点'),
      field: 'address',
      // fieldLabel:'enterpriseName',
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true
      },
    },
    {
      label: t('维保企业'),
      field: 'maintenanceEnterprise',
      component: 'TreeSelect',
      componentProps: {
        maxlength: 255,
        api:officeTreeData,
        pparams:{},
        onChange:(name,code)=>{
          record.value.maintenanceEnterpriseName = name;
        },
        disabled: true
      },
    },
    {
      label: t('消防队'),
      field: 'fireDepartment',
      component: 'TreeSelect',
      componentProps: {
        maxlength: 255,
        api:officeTreeData,
        params:{},
        onChange:(name,code)=>{
          record.value.fireDepartmentName = name;
        },
        disabled: true
      },
    },
    {
      label: t('隐患说明'),
      field: 'hazardDescription',
      component: 'Input',
      componentProps: {
        disabled: true
      }
    },
    {
      label: t('流程处理状态'),
      field: 'processStatus',
      show: false,  
      component: 'Input',
      componentProps: {
        disabled: true
      }
    },
    {
      label: t('监督员'),
      field: 'supervisorCode',
      fieldLabel:'supervisorName',
      show: false,  
      component: 'Input',
      componentProps: {
        disabled: true
      }
    },
    {
      label: t('企业员工判断处理方式'),
      field: 'handlingMethod',
      component: 'RadioGroup',
      componentProps: {
        options:[
          {label:t('误报'),value:'1'},
          {label:t('自行修理'),value:'2'},
          {label:t('转维保'),value:'3'}
        ],
      },
      show:()=>{
       return record.value.bpm.activityId=='Handling_method'
      }
    }, 
    {
      label: t('企业自行修理隐患方式'),
      field: 'selfRepairMethod',
      component: 'RadioGroup',
      componentProps: {
        options:[
          {label:t('直接处理'),value:'1'},
          {label:t('购买材料'),value:'2'},
        ],
        disabled: true
      },
      show:()=>{
       return record.value.bpm.activityId=='Administrator_approval'
      }
    },
    {
      label: t('购买清单'),
      field: 'purchasingList',
      component: 'Input',
      componentProps:{
        disabled: true
      }, 
      show:()=>{
       return record.value.bpm.activityId=='Administrator_approval'
      }
    },
    {
      label: t('是否超时'),
      field: 'currentlyTimeout',
      component: 'Select',
      componentProps:{
        options:[
          {label:t('是'),value:'是'},
          {label:t('否'),value:'否'}
        ],
        disabled: true
      }, 
    },
    {
      label: t('超时提示内容'),
      field: 'timeoutAlert',
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true
      },
    },
    // {
    //   label: t('异常图片上传'),
    //   field: 'dataMap',
    //   component: 'Upload',
    //   componentProps: {
    //     loadTime: computed(() => record.value.__t),
    //     bizKey: computed(() => record.value.id),
    //     fileUrl:computed(() => record.value.fileUrl),
    //     bizType: 'fireHazardProcess_image',
    //     uploadType: 'image',
    //     // onChange:(fileUrl)=>{
    //     //   record.value.hiddenUrl = fileUrl;
    //     // }
    //   },
    //   colProps: { md: 24, lg: 24 },
    //   show:()=>{
    //     return record.value.bpm.activityId=='False_reporting_upload'
    //   }
    // },
    {
      label: t('处理结果图片上传'),
      field: 'dataMap',
      component: 'Upload',
      componentProps: {
        loadTime: computed(() => record.value.__t),
        bizKey: computed(() => record.value.id),
        fileUrl:computed(() => record.value.fileUrl),
        bizType: 'fireHazardProcessResult_image',
        uploadType: 'image',
        maxNumber:1,
        // onChange:(fileUrl)=>{
        //   record.value.imageUrl = fileUrl;
        // }
      },
      colProps: { md: 24, lg: 24 },
      show:()=>{
        return record.value.bpm.activityId=='False_reporting_upload' || record.value.bpm.activityId=='Directly_handling_evidence'
      }
    },
    {
      label: t('建筑Id'),
      field: 'buildId',
      // fieldLabel:'buildName',
      show: false,  
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true
      },
    },
    {
      label: t('区域Id'),
      field: 'regionId',
      // fieldLabel:'regionName',
      show: false,  
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true
      },
    },
    {
      label: t('主体Id'),
      field: 'enterpriseId',
      // fieldLabel:'enterpriseName',
      show: false,  
      component: 'Input',
      componentProps: {
        maxlength: 255,
        disabled: true
      },
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { md: 24, lg: 12 },
  });

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await fireHazardProcessForm(data);
    FormResult.value = res;
    console.log('res',FormResult.value)
    imageFire.value = res.fireHazardProcess.hiddenUrl;
    imageResult.value = res.fireHazardProcess.imageUrl;
    record.value = (res.fireHazardProcess || {}) as FireHazardProcess;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setDrawerProps({ loading: false });
  });

  async function handleUserSelect({ task }, openUserSelectDrawer) {
    try {
      let data = await validate();
      data={
        ...data,
        hiddenUrl:(data.dataMap.fireHazardProcess_imageUrl != null) ? (data.dataMap.fireHazardProcess_imageUrl.split('?')[0]) : record.value.hiddenUrl,
        imageUrl:(data.dataMap.fireHazardProcessResult_imageUrl != null) ? (data.dataMap.fireHazardProcessResult_imageUrl.split('?')[0]) : record.value.imageUrl,
      }
      openUserSelectDrawer(true, {
        // 流程定义Key
        prodDefKey: 'fire_hazards',
        // 当前任务节点ID，默认为第一个节点ID
        activityId: task?.activityId || 'edit',
        // 提交给流程的变量，用于线条的条件计算
        variables: {
          initiator:data.initiator
        },
      });
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(error.message || t('common.validateError'));
      }
      console.log('error', error);
    }
  }





  async function handleValidate(_event: any, formData: any) {
    try {
      const data = await validate();
      console.log('validatedata',data)
      formData(true, data); // 将表单数据传递给 BpmButton
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(error.message || t('common.validateError'));
      }
      console.log('error', error);
    }
  }

  async function handleSubmit(event: any) {
    try {
      loadingRef.value = true;
      let data = event?.formData || (await validate()); // 接受 BpmButton 传递过来的表单数据
      data={
        ...data,
        hiddenUrl:(data.dataMap.fireHazardProcess_imageUrl != null) ? data.dataMap.fireHazardProcess_imageUrl : record.value.hiddenUrl,
        imageUrl:(data.dataMap.fireHazardProcessResult_imageUrl != null) ? data.dataMap.fireHazardProcessResult_imageUrl : record.value.imageUrl, 
        
      }
      data.bpm = Object.assign(data.bpm || {}, record.value.bpm); // 流程信息
      data.status = record.value.status; // 提交状态
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        tid: record.value.tid,
      };
      // console.log('submit', params, data, record);
      console.log('data',data)
      // console.log(params.methods1)
      const res = await fireHazardProcessSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(error.message || t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSuccess() {
    emit('success');
  }
</script>
<style lang="less" scoped>
.fireVeIm{
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin-bottom: 5%;
}
.fireImg {
  width: 20%;
  height: 200px;
}
.fireVideo {
  width: 20%;
  height: 200px;
}
</style>